<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\adminapi\controller;

use think\Db;

/**
 * @name【2.对帐单】
 * @baseurl【adminapi/Check】
 * @file【Check.php】
 */

class Check extends Base
{

    /**
     * @name【2.1对帐单列表】
     * @desc【】
     * @uri【index】
     * @method【post/get】
     * @table【p_check,p_check_item】
     * @param【
     *  year $ string $ 2018 $ 年份 $ 1 #
     *  company_id $ int $ 256 $ 用车ID $ 1#
     *  check_state $ int $ 0 $ 状态 $ 1#
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function index() {

        $P = input('param.');

        $year = input('param.year');
        $state = input('param.check_state');
        $company_id = input('param.company_id');


        $list = $months = $where = [];
        if($company_id) {

            if($year) {

                //所有月份
                $lastmonth = $year >= date('Y') ? date('n')-1 : 12;
                for($i=1;$i<=$lastmonth;$i++) {
                    $months[] = $year.'-'.str_pad($i,2,'0',STR_PAD_LEFT);
                }
                $where['month'] = ['IN',$months];
            }
            $list = Db::name('check')->where('company_id',$company_id)->where($where)->order('month DESC')->column('*','month');

            foreach($months AS $month) {
                $list[$month] = $list[$month] ?: ['id'=>0];
            }

        }

        return $this->retAll($list);
//		$company_id

    }
    /**
     * @name【查看对帐单】
     * @desc【】
     * @uri【detail】
     * @method【post/get】
     * @param【
     *  passenger_name $ string $  $ 乘车人  #
     *  orderer $ string $  $ 下单人  #
     *  approval $ string $  $ 审核人  #
     *  order_type $ int $  $ 订单类型  #
     *  page $ int $ 1 $ 分页  #
     *  export $ export $ 0 $ 分页  #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function detail() {

        $id = input('param.id');
        $page = input('param.page',1);
        $passenger_name = input('param.passenger_name')?'%'.input('param.passenger_name').'%':'%%';
        $orderer = input('param.orderer')?'%'.input('param.orderer').'%':'%%';
        $approval = input('param.approval');
        $order_type = input('param.order_type')?input('param.order_type'):'1,2,3';
        $export = input('param.export',0);

        //1.详情
        $check = Db::name('check')->alias('c')->join('company cu','cu.company_id = c.company_id')->where('id',$id)->find();
        //2.详细
        if($check) {

            $field = $export ? '*' : 'ci.id,ci.state,o.*,of.*,og.from_addr,og.to_addr,d.name AS driver_name';

            if($approval) {
                $check['items'] = Db::name('check_item')->alias('ci')
                    ->join('order o', 'o.order_id = ci.order_id')
                    ->join('order_fee of', 'of.order_id = ci.order_id')
                    ->join('order_gps og', 'og.order_id = o.order_id', 'left')
                    ->join('driver d', 'd.driver_id = o.driver_id', 'left')
                    ->where('check_id', $check['id'])->whereIn('ci.state', [1, 9])
                    ->where('o.passenger_name', 'like', $passenger_name)
                    ->where('o.orderer', 'like', $orderer)
                    ->where('o.approval', 'like', $approval)
                    ->where('o.order_type', 'in',$order_type)
                    ->limit(10)->page($page)->field($field)->select();
            }
            else{
                $check['items'] = Db::name('check_item')->alias('ci')
                    ->join('order o', 'o.order_id = ci.order_id')
                    ->join('order_fee of', 'of.order_id = ci.order_id')
                    ->join('order_gps og', 'og.order_id = o.order_id', 'left')
                    ->join('driver d', 'd.driver_id = o.driver_id', 'left')
                    ->where('check_id', $check['id'])->whereIn('ci.state', [1, 9])
                    ->where('o.passenger_name', 'like', $passenger_name)
                    ->where('o.orderer', 'like', $orderer)
                    ->where('o.order_type', 'in',$order_type)
                    ->limit(10)->page($page)->field($field)->select();
            }
            if($export && request()->isGet()) {

                return $this->xls("{$check['name']} {$check['month']} 第{$page}页 ",[],$check['items'] );

            } else {
                if($approval) {
                    $check['count'] = Db::name('check_item')->alias('ci')
                        ->join('order o', 'o.order_id = ci.order_id')
                        ->join('order_fee of', 'of.order_id = ci.order_id')
                        ->join('order_gps og', 'og.order_id = o.order_id', 'left')
                        ->join('driver d', 'd.driver_id = o.driver_id')
                        ->where('o.passenger_name', 'like', $passenger_name)
                        ->where('o.orderer', 'like', $orderer)
                        ->where('o.approval', 'like', $approval)
                        ->where('o.order_type', 'in',$order_type)
                        ->where('check_id', $check['id'])->whereIn('ci.state', [1, 9])->count();
                }
                else{
                    $check['count'] = Db::name('check_item')->alias('ci')
                        ->join('order o', 'o.order_id = ci.order_id')
                        ->join('order_gps og', 'og.order_id = o.order_id', 'left')
                        ->join('order_fee of', 'of.order_id = ci.order_id')
                        ->join('driver d', 'd.driver_id = o.driver_id')
                        ->where('o.passenger_name', 'like', $passenger_name)
                        ->where('o.orderer', 'like', $orderer)
                        ->where('o.order_type', 'in',$order_type)
                        ->where('check_id', $check['id'])->whereIn('ci.state', [1, 9])->count();
                }
            }


            return $this->retAll($check);
        }

        return $this->retError('查无对账单');
    }

    /**
     * @name【下载对帐单】
     * @desc【】
     * @uri【detail】
     * @method【post/get】
     * @param【
     *  passenger_name $ string $  $ 乘车人  #
     *  orderer $ string $  $ 下单人  #
     *  approval $ string $  $ 审核人  #
     *  order_type $ int $  $ 订单类型  #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function detail2excel() {

        $id = input('param.id');
        $page = input('param.page',1);
        $passenger_name = input('param.passenger_name')?'%'.input('param.passenger_name').'%':'%%';
        $orderer = input('param.orderer')?'%'.input('param.orderer').'%':'%%';
        $approval = input('param.approval');
        $order_type = input('param.order_type')?input('param.order_type'):'1,2,3';
        $export = input('param.export',0);

        $company_name = Db::name('check')
            ->where('id',$id)
            ->alias('ch')
            ->join('company co','co.company_id=ch.company_id','left')
            ->value('co.company_name');
        if($order_type == 2) {//企业订单
            //内容
            $field = 'o.order_no,o.ride_time,og.from_addr,og.to_addr,o.passenger_name,o.approval,o.order_type,o.use_type,o.use_explain,ct.car_type_name,d.name,c.number,of.discount,of.order_money,of.passenger_money,co.company_name';
            //标题
            $title = array("订单编号", "出发时间", "出发地点", "到达地点", "乘车人", "审批人", "用车类别", "用车类型", "用车说明", "订车类型", "司机姓名", "车牌号码","折扣","原价","结算金额","所属公司");
            //文件名
            $filename = $company_name.'公务用车(企业订单)明细';
        }
        else{//企业订单以外的订单
            //内容
            $field = 'o.order_no,o.ride_time,og.from_addr,og.to_addr,o.passenger_name,o.approval,o.order_type,o.use_type,o.use_explain,ct.car_type_name,d.name,c.number,of.passenger_money,co.company_name';
            //标题
            $title = array("订单编号", "出发时间", "出发地点", "到达地点", "乘车人", "审批人", "用车类别", "用车类型", "用车说明", "订车类型", "司机姓名", "车牌号码", "结算金额","所属公司");
            //文件名
            $filename = $company_name.'公务用车明细';
        }

        //1.详情
        $check = Db::name('check')->alias('c')->join('company cu','cu.company_id = c.company_id')->where('id',$id)->find();
        //2.详细
        if($check) {

            if($approval) {
                $check['items'] = Db::name('check_item')->alias('ci')
                    ->join('order o', 'o.order_id = ci.order_id')
                    ->join('order_fee of', 'of.order_id = ci.order_id')
                    ->join('order_gps og', 'og.order_id = o.order_id', 'left')
                    ->join('driver d', 'd.driver_id = o.driver_id', 'left')
                    ->join('car c', 'c.car_id = o.car_id', 'left')
                    ->join('car_type ct', 'ct.car_type_id = c.car_type_id', 'left')
                    ->join('company co', 'co.company_id = o.company_id', 'left')
                    ->where('check_id', $check['id'])->whereIn('ci.state', [1, 9])
                    ->where('o.passenger_name', 'like', $passenger_name)
                    ->where('o.orderer', 'like', $orderer)
                    ->where('o.approval', 'like', $approval)
                    ->where('o.order_type', 'in',$order_type)
                    ->field($field)
                    ->select();
            }
            else{
                $check['items'] = Db::name('check_item')->alias('ci')
                    ->join('order o', 'o.order_id = ci.order_id')
                    ->join('order_fee of', 'of.order_id = ci.order_id')
                    ->join('order_gps og', 'og.order_id = o.order_id', 'left')
                    ->join('driver d', 'd.driver_id = o.driver_id', 'left')
                    ->join('car c', 'c.car_id = o.car_id', 'left')
                    ->join('car_type ct', 'ct.car_type_id = c.car_type_id', 'left')
                    ->join('company co', 'co.company_id = o.company_id', 'left')
                    ->where('check_id', $check['id'])->whereIn('ci.state', [1, 9])
                    ->where('o.passenger_name', 'like', $passenger_name)
                    ->where('o.orderer', 'like', $orderer)
                    ->where('o.order_type', 'in',$order_type)
                    ->field($field)
                    ->select();
            }

            if ($check['items']) {
                echo "<table border='1'>";
                //标题
//                $title = $title;
                //文件名
//                $filename = $check['items'][0]['company_name'].$filename;
                header("Content-type:application/octet-stream");
                header("Accept-Ranges:bytes");
                header("Content-type:application/vnd.ms-excel");
                header("Content-Disposition:attachment;filename=" . $filename . ".xls");
                header("Pragma: no-cache");
                header("Expires: 0");
                if (!empty($title)) {
                    foreach ($title as $k => $v) {
                        $title[$k] = iconv("UTF-8", "GB2312", "<td>" . $title[$k] . "</td>");
                        echo $title[$k];
                    }
                    echo "</tr>";
                }
                if (!empty($check['items'])) {
                    foreach ($check['items'] as $key => $val) {
                        echo "<tr>";

                        if($check['items'][$key]['departure'] == ''){
                            $check['items'][$key]['departure'] = '暂无信息';
                        }

                        if($check['items'][$key]['destination'] == ''){
                            $check['items'][$key]['destination'] = '暂无信息';
                        }

                        if($check['items'][$key]['use_explain'] == ''){
                            $check['items'][$key]['use_explain'] = '暂无信息';
                        }

                        if($check['items'][$key]['order_type'] == '1'){
                            $check['items'][$key]['order_type'] = '公务订单';
                        }
                        else if($check['items'][$key]['order_type'] == '2'){
                            $check['items'][$key]['order_type'] = '企业订单';
                        }
                        else if($check['items'][$key]['order_type'] == '3'){
                            $check['items'][$key]['order_type'] = '个人订单';
                        }

                        if($check['items'][$key]['use_type'] == '0'){
                            $check['items'][$key]['use_type'] = '行政执法';
                        }
                        else if($check['items'][$key]['use_type'] == '1'){
                            $check['items'][$key]['use_type'] = '特殊公务';
                        }
                        else if($check['items'][$key]['use_type'] == '2'){
                            $check['items'][$key]['use_type'] = '重要会议';
                        }
                        else if($check['items'][$key]['use_type'] == '3'){
                            $check['items'][$key]['use_type'] = '机要通讯';
                        }
                        else if($check['items'][$key]['use_type'] == '4'){
                            $check['items'][$key]['use_type'] = '视察调研';
                        }
                        else if($check['items'][$key]['use_type'] == '5'){
                            $check['items'][$key]['use_type'] = '公务接待';
                        }

                        foreach ($val as $ck => $cv) {
                            $check['items'][$key][$ck] = iconv("UTF-8", "GB2312", "<td style=\"vnd.ms-excel.numberformat:@\">" . $check['items'][$key][$ck] . "</td>");
                            echo $check['items'][$key][$ck];
                        }
                        echo "</tr>";
                    }
                }
                else {
                    $this->error('无数据');
                }
            }
            else{
                $this->error('无数据');
            }

        }
        else{
            $this->error('无数据');
        }
    }

    /**
     * @name【生成对帐单】
     * @desc【】
     * @uri【creat】
     * @method【post/get】
     * @param【
     *  month $ string $ abc $ 年月 $ 1 #
     *  company_id $ int $ 1 $ 用车ID $ 1#
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function creat() {

        $month = input('param.month');
        $company_id = input('param.company_id');

        if(!$month || !$company_id) {
            return $this->retError('参数错误');
        }

        //是否已经生成
        $check = Db::name('check')->where(['company_id'=>$company_id,'month' => $month])->find();

        if(!$check) {

            $all = [];
            //订单统计
            $orders = Db::name('order')->alias('o')->join('order_fee of','o.order_id = of.order_id')->where('company_id',$company_id)->whereIn('order_state',[10,11])->whereLike('orders_time',$month.'%')->select();

            $oids = array_column($orders,'order_id');
            $total = array_sum(array_column($orders,'order_money'));

            //对账详情
            $check = ['company_id'=>$company_id,'month' => $month,'order_number'=>count($oids),'order_total'=>$total];
            $check['id'] = Db::name('check')->exp('datetime','NOW()')->insertGetId($check);

            if($check['id']) {

                foreach($oids AS $oid) {
                    $all[] = ['check_id'=>$check['id'],'order_id'=>$oid];
                }
                //插入对账
                if($all) {
                    Db::name('check_item')->insertAll($all);
                }

            } else {
                return $this->retError('生成失败，请重试');
            }

        }

        return $this->retAll($check);
//		return $this->retError('已经生成，请不要重复操作。尝试刷新列表页。');
    }

    /**
     * @name【管理后台审核】
     * @desc【待审核、待处理状态才能审核】
     * @uri【audit】
     * @method【post】
     * @param【
     *  id $ int $ abc $ 对账单ID $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function audit() {

        $id = input('post.id');

        $check = Db::name('check')->where('id',$id)->find();

        if(in_array($check['check_state'],[1,2])){
            $rslt = Db::name('check')->where('id',$id)->setField('check_state',3);

            return $this->retAll($rslt);
        }

        return $this->retError('状态错误，请刷新页面');

    }

    /**
     * @name【单位后台审核】
     * @desc【待确认状态才能确认，否则提示待确认】
     * @uri【confirm】
     * @method【post】
     * @param【
     *  id $ int $ 34 $ 对账单ID $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function confirm() {

        $id = input('post.id');

        $check = Db::name('check')->where('id',$id)->find();

        if(in_array($check['check_state'],[3])){
            $rslt = Db::name('check')->where('id',$id)->setField('check_state',4);

            //恢复额度
            if($rslt) {
                $quota = Db::name('CheckItem')->alias('ci')->join('OrderFee of','ci.order_id = of.order_id')->where(['check_id'=>$id,'state'=>9])->sum('order_money');
                Db::name('CarUse')->where('company_id',$check['company_id'])->setDec('used_quota',$quota);
            }
            return $this->retAll($rslt);
        }

        return $this->retError('状态错误，请等待运营处理');

    }
    /**
     * @name【对帐单填写快递单号】
     * @desc【只有状态为已确认的对账单能填写快递单号】
     * @uri【express】
     * @method【post】
     * @param【
     *  id $ int $ 1 $ 对帐单ID $ 1 #
     *  express $ string $ abc $ 快递单号 $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function express() {

        $id = input('post.id');
        $express = input('post.express');

        $check = Db::name('check')->where('id',$id)->find();

        if($check['check_state'] == 4){
            $rslt = Db::name('check')->where('id',$id)->setField('express',$express);

            return $this->retAll($rslt);
        }

        return $this->retError('未确认的对帐单，不能填写快递单号');
    }

    /**
     * @name【条目设置为无效】
     * @desc【条目无效，对应账单改为待处理】
     * @uri【cancel】
     * @method【post/get】
     * @param【
     *  id $ int $ abc $ 条目ID $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function cancel() {

        $id = input('post.id');

        if($id) {

            $item = Db::name('CheckItem')->alias('ci')
                ->join('order_fee of','ci.order_id = of.order_id')
                ->where('ci.id',$id)->find();

            if($item != 9) {
                $rslt = Db::name('check')->where('id',$item['check_id'])->dec('order_number')->dec('order_total',$item['order_money'])->setField('check_state',2);
                $rslt && $rslt = Db::name('CheckItem')->where('id',$id)->setField('state',9);

                return $this->retAll($rslt);
            }

            return $this->retError('该条目已经取消，请勿重复操作。');

        }

        return $this->retError('参数错误');
    }
    /**
     * @name【额度流水】
     * @desc【】
     * @uri【waste】
     * @method【post/get】
     * @param【
     *  company_id $ int $ 243 $ 用车公司ID $ 1 #
     *  page $ int $ 1 $ 页数 $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * 】
     */
    public function waste() {

        $company_id = input('post.company_id');
        $page = input('post.page',1);

        $data = [];
        $data['count'] = Db::name('order')->alias('o')
            ->join('OrderFee of','o.order_id = of.order_id')
            ->join('CheckItem ci','ci.order_id = o.order_id')
            ->where('o.company_id',$company_id)->whereIn('o.order_state',[10,11])
            ->count();

        $data['list'] = Db::name('order')->alias('o')
            ->join('OrderFee of','o.order_id = of.order_id')
            ->join('CheckItem ci','ci.order_id = o.order_id')
            ->where('o.company_id',$company_id)->whereIn('o.order_state',[10,11])
            ->field('order_time,order_no,order_money,ci.state')->order('order_time DESC')->limit(10)->page($page)->select();
        return $this->retAll($data);

    }


}
